﻿using GodSharp;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Common;
using ZK.InterfaceServer;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 山东领军 红绿交通灯
    /// </summary>
    public class TrafficLightBLL : BaseBLL
    {
        private readonly GodSerialPort _serialPort;
        private bool _isOpened;
        public int lightStatus = 0;
        public bool IsInit = false;
        public TrafficLightBLL()
        {

        }

        public TrafficLightBLL(Models.TerminalM terminalM)
        {
            try
            {
                this.IsInit = true;
                this.terminal = terminalM;
            }
            catch (Exception ex)
            {
               // WebApiServer.AddHardWareLog(terminalM.name, ex.Message, "网络连接失败");
                Common.Log4.LogManage.WriteErr("红绿灯初始化 " + ex.ToString() + " 红绿灯信息 串口号：" + terminalM.com);
            }
        }


        public void RedLight0()
        {
            Task.Factory.StartNew(() => {
                try
                {
                    lightStatus = 1;
                    ///创建客户端
                    var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                    ///IP地址
                    IPAddress ip = IPAddress.Parse(this.terminal.ip);
                    ///端口号
                    IPEndPoint endPoint = new IPEndPoint(ip, (int)this.terminal.port);
                    ///建立与服务器的远程连接
                    client.Connect(endPoint);
                    ///线程问题
                    //Thread thread = new Thread(ReciveMsg);
                    //thread.IsBackground = true;
                    //thread.Start(client);
                    //将字符串指令转换为byte数组
                    // byte[] buf = System.Text.Encoding.Default.GetBytes("AT+STACH" + num + "=1,1\r\n");
                    //发送AT指令
                    client.Send(new byte[]
                {
                0x77,
                0x75,
                0x30,
                0x00,
                0x0C,
                0x04,
                0x0C,
                0x0C,
                0x0D,
                0x0A
                });

                    byte[] recbuf = new byte[1024];//真正使用时，接收缓冲区需要适当的调整
                                                   //等待硬件响应命令，接收到的数据为byte数组
                                                   //会等待到有数据返回为止
                    int recLen = client.Receive(recbuf);
                    client.Close();
                    //将byte数组转为字符串
                    string str = System.Text.Encoding.Default.GetString(recbuf);
                }
                catch (Exception ex)
                {
                    Common.Log4.LogManage.WriteErr(ex.ToString());
                }
            }).Wait(3000);

        }

        public void GreenLight0()
        {
            Task.Factory.StartNew(() => {
                try
                {
                    lightStatus = 2;
                    ///创建客户端
                    var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                    ///IP地址
                    IPAddress ip = IPAddress.Parse(this.terminal.ip);
                    ///端口号
                    IPEndPoint endPoint = new IPEndPoint(ip, (int)this.terminal.port);
                    ///建立与服务器的远程连接
                    client.Connect(endPoint);
                    ///线程问题
                    //Thread thread = new Thread(ReciveMsg);
                    //thread.IsBackground = true;
                    //thread.Start(client);
                    //将字符串指令转换为byte数组
                    // byte[] buf = System.Text.Encoding.Default.GetBytes("AT+STACH" + num + "=1,1\r\n");
                    //发送AT指令
                    client.Send(new byte[]
                {
                0x77,
                0x75,
                0x30,
                0x00,
                0x04,
                0x0C,
                0x0C,
                0x0C,
                0x0D,
                0x0A
                });

                    byte[] recbuf = new byte[1024];//真正使用时，接收缓冲区需要适当的调整
                                                   //等待硬件响应命令，接收到的数据为byte数组
                                                   //会等待到有数据返回为止
                    int recLen = client.Receive(recbuf);
                    client.Close();
                }
                catch (Exception ex)
                {
                    Common.Log4.LogManage.WriteErr(ex.ToString());
                }
            }).Wait(3000);
        }

        public void LightOff()
        {
            try
            {
                _serialPort.Write(new byte[]
                {
                0x77,
                0x75,
                0x30,
                0x00,
                0x00,
                0x00,
                0x00,
                0x00,
                0x0D,
                0x0A
                });
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr("红绿灯灭灯" + ex.ToString());
                Common.DelegateHelper.InfoMessageEvent?.Invoke("红绿灯灭灯出错");
            }
        }

        public void Open()
        {
            _isOpened = _serialPort.Open();
            ReopenIfClosed();
        }

        public void Close()
        {
            _isOpened = !_serialPort.Close();
        }

        private void ReopenIfClosed()
        {
            if (_isOpened)
            {
                //await Task.Delay(1000);
                //await Task.Run(() =>
                //{
                //    if (!_serialPort.IsOpen)
                //    {
                //        _serialPort.Close();
                //        _serialPort.Open();
                //    }
                //    ReopenIfClosed();
                //});
            }
            else
            {
                _serialPort.Close();
            }
        }



        public override bool GreenLight()
        {
            GreenLight0();
            return true;
        }

        public override bool RedLight()
        {
            RedLight0();
            return true;
        }


    }
}
